(ns cljsso.logger
  (:require
   [taoensso.timbre :as timbre]
   [cljsso.config :refer [props]]
   [noir.session :as session]))


(def ^:dynamic *request-id* nil)


(defn wrap-request-logger [handler]
  "Wrap a logger logging request uri, username, ip address and response
  time. A random *request-id* will be associated with every request."
  (fn [req]
    (let [now        (System/currentTimeMillis)
          request-id (or (:request-id req) (rand-int 0xffff))]
      (try
        (binding [*request-id* request-id]
          (handler (assoc req :request-id request-id)))
        (catch Exception e
          (timbre/error e (str request-id "Exception: " (.getMessage e) " on Req: " req ))
          (throw e))
        (finally
          (if (= :debug (:log-level props))
            (timbre/debug
             request-id
             " Session:" @session/*noir-session*
             " Req:" req
             " Time:" (- (System/currentTimeMillis) now))
            (timbre/info
             request-id
             " User:" (session/get-in (:uid-session-key props))
             " Req:" (req :uri)
             " From:" (or (get-in req [:headers "x-real-ip"]) (:remote-addr req))
             " Time:" (- (System/currentTimeMillis) now))))))))
